package com.qianfeng.rencai.security.service;

import com.qianfeng.rencai.mapper.SysUserMapper;
import com.qianfeng.rencai.pojo.SysUser;
import com.qianfeng.rencai.security.bean.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * Created by wenka on 2022/3/30 16:08
 *
 * @author wenkaixin
 * @version 1.0
 * @since 1.0
 */
@Component
public class MyUserSetailService implements UserDetailsService {
    private SysUserMapper sysUserMapper;


    @Autowired
    public void setSysUserMapper(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 当我们登录的时候传递过来的用户名
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.findByUserName(username);
        //如果用户不存在怎么办
        if (user==null){
            throw new UsernameNotFoundException("用户名密码不存在");
        }
        if (user.getStatus()==0){
            throw new AccountExpiredException("账号被封禁");
        }
        //参数一用户名
        //参数二查询到的密码
        //参数三用户有的权限，权限可以后面查询，可以在这里先查询，设置进去，也可以后面更新，但我个人建议先写个空的
        //因为可能账号密码不对，你要获取权限需要查询数据库，就白查询了
        //如果一个类本身的功能不足以满足我们的需求的时候可以通过继承扩展

        return new BaseUser(username,user.getPassword(),new ArrayList<>(),user.getUserId());
    }
}
